﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

using WF.BusinessObject;
using Com.UI.Web;
using Com.DAO;
using System.Web.Security;

namespace WF.Common
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseUserControl : System.Web.UI.UserControl
    {
        /// <summary>
        /// 
        /// </summary>
        protected DataManager DataManager = new DataManager();
        /// <summary>
        /// 
        /// </summary>
        // protected string cchrWebUrl = ""; //System.Configuration.ConfigurationManager.AppSettings["CCAIWebUrl"].ToString();

        private ArrayList submitButtons = new ArrayList(3);
        /// <summary>
        /// 
        /// </summary>
        public struct LoginUserInfo
        {
            public string EmpID;
            public string EmpNo;
            public string EmpName;
            public string UserID;
            public string DeptID;
            public string DeptName;
            public string DeptPath;
            public string RoleID;
            public string RoleName;
            public string HaveMultiRole;

        }

        public LoginUserInfo LogonUser;
        protected string AppPath;
        protected string CmdType = "";

        #region 工作流相关

        public struct WorkFlowData
        {
            public string ApplyID;
            public string CurrentActivityName;
            public string CurrentActivityDisplayName;
            public bool IsWFApproval;
        }

        public WorkFlowData WorkFlowControl;

        public bool IsWF
        {
            get
            {
                return WorkFlowControl.IsWFApproval;
            }
            set
            {
                WorkFlowControl.IsWFApproval = value;
            }
        }
        #endregion 工作流相关


        protected bool IsRebind = false;
        /// <summary>
        /// 
        /// </summary>
        public BaseUserControl()
        {
            OpenDataDB();
            DataGridUtils.ClearDataGridAction();
        }

        /// <summary>
        /// 页面初始化

        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            //this.cchrWebUrl = this.Application["AppPath"].ToString();
            string ascxName = this.GetType().Name;

            if (ascxName != "components_contract_contractadjustreport_ascx")
            {
                this.Response.Expires = 0;
                this.Response.CacheControl = "no-cache";
            }

            base.OnInit(e);


            this.Unload += new EventHandler(Page_UnLoad);
            SetCommandType();
            this.AppPath = Application["AppPath"].ToString();

            string verNo = Assembly.Load("WF.Web").GetName().Version.ToString();
            Page.Title = "流程审批系统 V" + verNo;

            try
            {
                this.IsRebind = Convert.ToBoolean(this.Request["hidIsRebind"]);
            }
            catch
            {
                this.IsRebind = false;
            }

            this.CheckLogin();//检查Session状态

        }


        /// <summary>
        /// 获取当前页面的 DataManager
        /// </summary>
        /// <returns></returns>
        public DataManager GetDataManager()
        {
            return this.DataManager;
        }

        /// <summary>
        /// 打开数据库连接

        /// </summary>
        protected void OpenDataDB()
        {
            try
            {
                if (this.DataManager.IsClosed)
                {
                    this.DataManager.OpenWithConfig();
                }

            }
            catch
            {
                throw new Exception("打开数据库连接失败！");
            }
        }

        /// <summary>
        /// 登录成功后，把SESSION值赋给结构体
        /// </summary>
        protected void AddLoginValue(UserProfile up)
        {
            this.LogonUser.UserID = up.LoginName;
            this.LogonUser.EmpID = up.EmpID;
            this.LogonUser.EmpNo = up.EmpNo;
            this.LogonUser.EmpName = up.Empname;
            this.LogonUser.DeptID = up.DeptID;
            this.LogonUser.DeptName = up.DeptName;
            this.LogonUser.DeptPath = up.DeptPath;
            this.LogonUser.RoleID = up.RoleID;
            this.LogonUser.RoleName = up.RoleName;
            this.LogonUser.HaveMultiRole = up.HaveMutilRole ? "1" : "0";
        }


        /// <summary>
        /// 页面卸载时，关掉数据库连接

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void Page_UnLoad(object sender, System.EventArgs e)
        {
            try
            {
                if (!this.DataManager.IsClosed)
                {
                    this.DataManager.Close();
                }
            }
            catch (Exception ex)
            {
                CentaUtil.SendExceptionMessage(this.Page, ex);
            }
        }

        /// <summary>
        /// 错误处理
        /// </summary>
        /// <param name="e"></param>
        protected void ExceptionHandle(Exception e)
        {
            if (e.Message.IndexOf("线程正被中止") >= 0 || e.Message.IndexOf("正在中止线程") >= 0)
            {
                return;
            }

            if (e.Message.IndexOf("常规网络错误") >= 0)
            {
                if (!this.IsPostBack)
                {
                    this.Response.Redirect(this.Request.RawUrl);
                }
                else
                {
                    this.ShowMessage(Page, "网络错误，请重新执行您刚才的操作!", true);
                    return;
                }
            }

            CentaUtil.ExceptionHandle(this.Page, e);
        }

        /// <summary>
        /// 检查Sesssion状态，如果Session过期，则需要返回登录页面重新登录

        /// 
        /// </summary>
        protected void CheckLogin()
        {
            SessionManager sm = new SessionManager();
            if (sm.CurrentUser.LoginName == null)
            //if(Session[SessionKeys.CurrentUser] == null)
            {
                ReLogin();
            }
            else
            {
                AddLoginValue(sm.CurrentUser);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected void ReLogin()
        {
            string typeName = this.GetType().Name;
            if (typeName != "components_login_login_ascx")
            {
                this.ShowMessage("操作超时，请重新登录！");
                FormsAuthentication.SignOut();
                string s = "window.parent.location='Login.aspx';";
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", s, true);
                //string loginUrl = Application["AppPath"].ToString() + "login.aspx?t=" + DateTime.Now.Ticks;
                //string script = "<script language='javascript'>window.top.document.location='" + loginUrl + "';</script>";                
                //Response.Write(script);
                Response.End();
            }
        }


        #region 页面动作
        /// <summary>
        /// 设置页面动作
        /// </summary>
        protected void SetCommandType()
        {
            string cmdTypeName = this.GetCmdTypeName();

            if (this.FindControl("lblCmdType") != null)
            {
                Label lblCT = (Label)this.FindControl("lblCmdType");
                lblCT.Text = cmdTypeName;
                if (!(lblCT.Text.IndexOf(">>") > -1))
                {
                    lblCT.Text = " >> " + lblCT.Text;
                }
                lblCT.Visible = true;
            }
        }

        protected string GetCmdTypeName()
        {
            string rtn = "";
            string cmdType = this.Request.QueryString["CmdType"];
            if (cmdType != null)
            {
                this.CmdType = cmdType.ToUpper();
                if (this.CmdType == "ADD")
                {
                    rtn = "新增";
                }
                else if (this.CmdType == "EDIT")
                {
                    rtn = "编辑";
                }
                else if (this.CmdType == "MOD")
                {
                    rtn = "修改";
                }
                else if (this.CmdType == "DEL")
                {
                    rtn = "删除";
                }
                else if (this.CmdType == "VIEW")
                {
                    rtn = "浏览";
                }
                else if (this.CmdType == "AUDIT")
                {
                    rtn = "审核";
                }
                else if (this.CmdType == "SUBMIT")
                {
                    rtn = "提交";
                }
            }
            return rtn;
        }
        protected void SetFocus(System.Web.UI.Control control)
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "setfocus", "<script language='javascript'>document.all('" + control.ClientID + "').focus(); document.all('" + control.ClientID + "').select();</script>");
        }
        #endregion

        /// <summary>
        /// 关闭使用了Ajax技术的窗口
        /// </summary>
        /// <param name="control">所属对象，一般用this或this.Page或UpdatePanel的ID</param>
        protected void AjaxWindowClose(Control control)
        {
            control.Page.ClientScript.RegisterStartupScript(control.GetType(), "Close", "window.close();", true);

        }

        /// <summary>
        /// 从使用了Ajax技术的模态窗口返回值

        /// </summary>
        /// <param name="control">所属对象，一般为this或this.Page</param>
        /// <param name="returnValue">返回值</param>
        protected void AjaxSetWindowReturnValue(Control control, string returnValue)
        {
            string script = "window.returnValue=\"" + returnValue + "\";";
            control.Page.ClientScript.RegisterStartupScript(control.GetType(), "ReturnValue", script, true);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="location"></param>
        protected void WindowHistoryGo(int location)
        {
            //this.Response.Write("<script language=javascript>window.history.go(" + location.ToString() + ")</script>");
            string script = "<script language=javascript>window.history.go(" + location.ToString() + ")</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "HisGo", script);
        }

        protected void WindowClose()
        {
            this.Response.Write("<script language='javascript'>window.close();</script>");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="returnValue"></param>
        protected void SetWindowReturnValue(string returnValue)
        {
            this.Response.Write("<script language='javascript'>window.returnValue=\"" + returnValue + "\";</script>");
            //string script = "<script type='text/javascript'>window.returnValue=\"" + returnValue + "\";</script>";
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "Return", script,true);

        }

        /// <summary>
        /// 在使用Ajax技术的窗口中显示弹出式消息
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="isAlertMessage">是否弹出式显示消息</param>
        protected void AjaxShowMessage(string message, bool isAlertMessage)
        {
            Messages.AjaxShowMessage(this, message, isAlertMessage);
        }

        /// <summary>
        /// 在使用Ajax技术的窗口中显示弹出式消息,针对局部刷新

        /// </summary>
        /// <param name="control"></param>
        /// <param name="message"></param>
        /// <param name="isAlertMessage"></param>
        protected void AjaxShowMessage(Control control, string message, bool isAlertMessage)
        {
            Messages.AjaxShowMessage(control, message, isAlertMessage);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="control"></param>
        /// <param name="message"></param>
        /// <param name="isAlertMessage"></param>
        protected void ShowMessage(Control control, string message, bool isAlertMessage)
        {
            Messages.ShowMessage(control, message, isAlertMessage);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isAlertMessage"></param>
        protected void ShowNoPowerMessage(bool isAlertMessage)
        {
            this.ShowMessage("没有此项操作权限！", isAlertMessage);
        }

        /// <summary>
        /// 显示页面提示信息
        /// </summary>
        /// <param name="message">提示信息</param>
        /// <param name="isAlertMessage">是否用Alert窗口提示</param>
        protected void ShowMessage(string message, bool isAlertMessage)
        {
            if (isAlertMessage)
            {
                Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "error", "<script type='text/javascript'>alert(\"" + message + "\")</script>");
            }
            else
            {
                if (this.FindControl("lblErrorMessage") != null)
                {
                    Label lblErrorMsg = (Label)this.FindControl("lblErrorMessage");
                    lblErrorMsg.Visible = true;
                    lblErrorMsg.Text = message;
                }
            }
        }

        /// <summary>
        /// 直接显示
        /// </summary>
        /// <param name="message"></param>
        protected void ShowMessage(string message)
        {
            string script = "<script type='text/javascript'>alert('" + message + "');</script>";
            Response.Write(script);
            //Page.ClientScript.RegisterStartupScript(this.Page.GetType(),"Warning",script);
        }
        /// <summary>
        /// 显示信息,适用于Window.close()前提示信息，比如页面加载时，相关条件不符时

        /// 弹出提示信息，随后关闭窗口用。

        /// </summary>
        /// <param name="message"></param>

        protected void ShowWarningMessage(string message)
        {
            string script = "<script type='text/javascript'>alert('" + message + "');window.close();</script>";
            Response.Write(script);
            //Page.ClientScript.RegisterStartupScript(this.Page.GetType(),"Warning",script);
        }

        #region 日志记录
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="operateNo"></param>
        /// <param name="bizEntity"></param>
        /// 
        protected string GetClientOSInfo()
        {
            string clientname;
            System.Net.IPHostEntry ihe;
            System.Net.IPAddress ip = System.Net.IPAddress.Parse(Request.UserHostAddress);
            try
            {
                ihe = System.Net.Dns.GetHostEntry(ip);
                //机器名

                clientname = ihe.HostName.Replace(".centaline.com.cn", "");
            }
            catch
            {
                clientname = "未知主机名";
            }
            //浏览器

            string NavInfo = Request.Browser.Browser + " " + Request.Browser.Version;
            //操作系统
            string OS = CentaUtil.GetOSNameByUserAgent(Request.ServerVariables["HTTP_USER_AGENT"]);
            return clientname + "/" + OS + "/" + NavInfo;
        }

        protected void Log(string operateNo, Com.DAO.BusinessEntiry bizEntity)
        {
            try
            {
                Log log = new Log(this.DataManager);
                log.SetProperty("LogID", CentaUtil.GetNewGUID());
                log.SetProperty("OperateNo", operateNo);
                log.SetProperty("OperateName", ""); //Operate.GetOperateContentByNo(operateNo, this.DataManager));
                log.SetProperty("OpContent", bizEntity.GetUpdateLog());
                log.SetProperty("OpTable", bizEntity.TableName);
                log.SetProperty("KeyID", bizEntity.RowID);
                log.SetProperty("DeptID", this.LogonUser.DeptID);
                log.SetProperty("EmpID", this.LogonUser.EmpID);
                log.SetProperty("ClientIP", this.Request.UserHostAddress);
                log.SetProperty("ClientOSInfo", GetClientOSInfo());
                log.Save(!this.DataManager.IsBeginTrasaction);
            }
            catch (Exception ex)
            {
                this.ExceptionHandle(ex);
            }
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="operateNo">操作编号</param>
        /// <param name="bizEntity">BusinessEntiry对象</param>
        /// <param name="tagColumnName">行标识值，如员工名，成交编号等</param>
        /// <param name="tagDisplayName">行标识的显示名，如“员工姓名”</param>
        protected void Log(string operateNo, Com.DAO.BusinessEntiry bizEntity, string tagColumnName, string tagDisplayName)
        {
            try
            {
                string operateName = "";    // Operate.GetOperateContentByNo(operateNo, this.DataManager);
                Log log = new Log(this.DataManager);
                log.SetProperty("LogID", CentaUtil.GetNewGUID());
                log.SetProperty("OperateNo", operateNo);
                log.SetProperty("OperateName", operateName);
                string content = operateName + "\n\r" + tagDisplayName + "为" + bizEntity.GetPropertyValue(tagColumnName) + "\n\r" + bizEntity.GetUpdateLog();
                log.SetProperty("OpContent", content);
                log.SetProperty("OpTable", bizEntity.TableName);
                log.SetProperty("KeyID", bizEntity.RowID);
                log.SetProperty("DeptID", this.LogonUser.DeptID);
                log.SetProperty("EmpID", this.LogonUser.EmpID);
                log.SetProperty("ClientIP", this.Request.UserHostAddress);

                log.SetProperty("ClientOSInfo", GetClientOSInfo());
                log.Save(!this.DataManager.IsBeginTrasaction);
            }
            catch (Exception ex)
            {
                this.ExceptionHandle(ex);
            }
        }

        protected void Log(string operateNo, string content, string tableName, string keyValue)
        {
            try
            {
                Log log = new Log(this.DataManager);
                log.SetProperty("LogID", CentaUtil.GetNewGUID());
                log.SetProperty("OperateNo", operateNo);
                log.SetProperty("OperateName", "");//Operate.GetOperateContentByNo(operateNo, this.DataManager));
                log.SetProperty("OpContent", content);
                log.SetProperty("OpTable", tableName);
                log.SetProperty("KeyID", keyValue);
                log.SetProperty("DeptID", this.LogonUser.DeptID);
                log.SetProperty("EmpID", this.LogonUser.EmpID);
                log.SetProperty("ClientIP", this.Request.UserHostAddress);
                log.SetProperty("ClientOSInfo", GetClientOSInfo());
                log.Save(!this.DataManager.IsBeginTrasaction);
            }
            catch (Exception ex)
            {
                this.ExceptionHandle(ex);
            }
        }

        protected void Log(string operateNo, string operateName, string content, string tableName, string keyValue)
        {
            try
            {
                Log log = new Log(this.DataManager);
                log.SetProperty("LogID", CentaUtil.GetNewGUID());
                log.SetProperty("OperateNo", operateNo);
                log.SetProperty("OperateName", operateName);
                log.SetProperty("OpContent", content);
                log.SetProperty("OpTable", tableName);
                log.SetProperty("KeyID", keyValue);
                log.SetProperty("DeptID", this.Page.Session["DeptID"].ToString());
                log.SetProperty("EmpID", this.Page.Session["EmpID"].ToString());
                log.SetProperty("ClientIP", this.Request.UserHostAddress);
                log.SetProperty("ClientOSInfo", GetClientOSInfo());
                log.Save(!this.DataManager.IsBeginTrasaction);
            }
            catch (Exception ex)
            {
                this.ExceptionHandle(ex);
            }
        }

        /// <summary>
        /// 主要用于删除
        /// </summary>
        /// <param name="operateNo"></param>
        /// <param name="tableName"></param>
        /// <param name="keyColumn"></param>
        /// <param name="keyValue"></param>
        /// <param name="tagColumnName"></param>
        /// <param name="tagDisplayName"></param>
        protected void Log(string operateNo, string tableName, string keyColumn, string keyValue, string tagColumnName, string tagDisplayName)
        {
            try
            {
                BusinessEntiry entity = new BusinessEntiry(this.DataManager, tableName, keyColumn);
                if (entity.OpenByKeyValue(keyValue))
                {
                    string operateName = "";// Operate.GetOperateContentByNo(operateNo, this.DataManager);
                    Log log = new Log(this.DataManager);
                    log.SetProperty("LogID", CentaUtil.GetNewGUID());
                    log.SetProperty("OperateNo", operateNo);
                    log.SetProperty("OperateName", operateName);
                    string content = operateName + "\n\r" + tagDisplayName + "为" + entity.GetPropertyValue(tagColumnName);
                    log.SetProperty("OpContent", content);
                    log.SetProperty("OpTable", tableName);
                    log.SetProperty("KeyID", keyValue);
                    log.SetProperty("DeptID", this.Page.Session["DeptID"].ToString());
                    log.SetProperty("EmpID", this.Page.Session["EmpID"].ToString());
                    log.SetProperty("ClientIP", this.Request.UserHostAddress);
                    log.SetProperty("ClientOSInfo", GetClientOSInfo());
                    log.Save(!this.DataManager.IsBeginTrasaction);
                }
            }
            catch (Exception ex)
            {
                this.ExceptionHandle(ex);
            }
        }
        #endregion


        #region 检查权限

        /// <summary>
        /// 根据操作编号检查当前用户的部门权限
        /// </summary>
        /// <param name="operateNo">操作编号</param>
        /// <param name="deptID">操作对象所属部门</param>
        ///	<param name="isShowMessage">是否显示提示信息</param>
        ///	<param name="isAlertMessage">是否弹出Alert窗口提示，弹出后是否关闭</param>
        /// <returns></returns>
        protected bool CheckDeptRight(string operateNo, string deptID, bool isShowMessage, bool isAlertMessage)
        {
            //////bool rtn = User.CheckRight(this.LogonUser.EmpID ,operateNo ,deptID ,this.DataManager);
            ////if (this.LogonUser.EmpID == null || this.LogonUser.RoleID == null)
            ////{
            ////    ReLogin();
            ////    return false;
            ////}
            ////else
            //{
            //    bool rtn = User.CheckRight(this.LogonUser.EmpID, this.LogonUser.RoleID, operateNo, deptID, this.LogonUser.DeptID, this.DataManager);
            //    if (!rtn && isShowMessage)
            //    {
            //        this.ShowWarningMessage("无此操作权限！");
            //       // this.ShowNoPowerMessage(isAlertMessage);
            //    }
            //    return rtn;
            //}
            return true;
        }


        /// <summary>
        /// 根据操作编号检查当前用户的个人操作权限
        /// </summary>
        /// <param name="operateNo">操作编号</param>

        /// <returns></returns>
        protected bool CheckPersonalRight(string operateNo)
        {
            if (this.LogonUser.RoleID == null)
            {
                Session.Abandon();
                return false;
            }
            //bool rtn = User.CheckRight(this.LogonUser.RoleID, operateNo, this.DataManager);
            bool rtn = true;
            return rtn;
        }

        /// <summary>
        /// 根据操作编号检查当前用户的个人操作权限
        /// </summary>
        /// <param name="operateNo">操作编号</param>
        ///	<param name="isShowMessage">是否显示提示信息</param>
        ///	<param name="isAlertMessage">是否弹出Alert窗口提示</param>
        /// <returns></returns>
        protected bool CheckPersonalRight(string operateNo, bool isShowMessage, bool isAlertMessage)
        {
            //    if (this.LogonUser.RoleID == null)
            //    {
            //        Session.Abandon();
            //        return false;
            //    }
            //    bool rtn = User.CheckRight(this.LogonUser.RoleID, operateNo, this.DataManager);
            //    if (!rtn && isShowMessage)
            //    {
            //        this.ShowNoPowerMessage(isAlertMessage);
            //    }
            //    return rtn;
            return true;
        }

        /// <summary>
        /// 根据操作编号检查当前用户的个人操作权限
        /// </summary>
        /// <param name="operateNo">操作编号</param>
        /// <param name="cmdType">当前操作类型</param>
        ///	<param name="isShowMessage">是否显示提示信息</param>
        /// <param name="isHideSubmitButton">是否隐藏提交按钮</param>
        /// <returns></returns>
        protected bool CheckPersonalRight(string operateNo, string cmdType, bool isShowMessage, bool isHideSubmitButton)
        {
            bool rtn = true;
            if (this.CmdType == cmdType.ToUpper())
            {
                rtn = CheckPersonalRight(operateNo, isShowMessage, false);
                if (!rtn)
                {
                    if (isHideSubmitButton)
                    {
                        foreach (object o in this.submitButtons)
                        {
                            Button button = (Button)o;
                            button.Visible = false;
                        }
                    }
                }
            }
            return rtn;
        }

        /// <summary>
        /// 判断成交是否是当前用户的，如果是判断用户是否有指定操作的权限
        /// </summary>
        /// <param name="operateNo">操作编号</param>
        /// <param name="contractID">成交ID</param>
        /// <param name="isShowMessage">是否显示提示信息</param>
        /// <param name="isAlertMessage">是否弹出Alert窗口提示</param>
        /// <returns></returns>
        protected bool CheckMyContract(string operateNo, string contractID, bool isShowMessage, bool isAlertMessage)
        {
            bool rtn = false;
            string sql;
            if (this.LogonUser.RoleName == "按揭员" || this.LogonUser.RoleName == "物业顾问")
            {

                sql = String.Format(@"select empid from F_Forward where forwardempid ='{0}' ", this.LogonUser.EmpID);

                string empScope = WF.Common.CentaUtil.GetTableColString(this.DataManager, sql, "EmpID");
                if (empScope.Trim() != "")
                {
                    empScope = "(" + empScope + ")";
                    sql = "(select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID + "' OR EmpID IN " + empScope
                        + " union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID + "' OR EmpID IN " + empScope
                        + " Union Select b.ContractID From CT_CommisionAdjustAssigns a Inner Join CT_CommisionAdjust b on a.AdjustID=b.AdjustID "
                        + " Where a.CommRatePer<>0 and a.EmpID='" + this.LogonUser.EmpID + "' OR a.EmpID IN " + empScope + ")";
                }
                else
                {
                    sql = "(select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID + "' "
                        + " union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID + "'"
                        + " Union Select b.ContractID From CT_CommisionAdjustAssigns a Inner Join CT_CommisionAdjust b on a.AdjustID=b.AdjustID "
                        + " Where a.CommRatePer<>0 and a.EmpID='" + this.LogonUser.EmpID + "')";
                }
            }
            else
            {
                sql = "select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID
                    + "' and ContractID='" + contractID + "' "
                    + "union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID
                    + "' and ContractID='" + contractID + "'";

            }

            DataSet ds = CentaUtil.SelectDataSet(this.DataManager, sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                rtn = this.CheckPersonalRight(operateNo, isShowMessage, isAlertMessage);
            }
            else if (isShowMessage)
            {
                this.ShowNoPowerMessage(isAlertMessage);
            }

            return rtn;
        }

        /// <summary>
        /// 获取部门权限查询范围
        /// </summary>
        /// <returns></returns>
        protected string GetDeptRightCondition()
        {
            //string rtn = "(select OpObjectID from SYS_UserOpScope Where DeptOrArea=0 and EmpID='" + this.LogonUser.EmpID + "')";
            string rtn = "";
            if (this.Session["DeptScope"] == null || this.Session["DeptScope"].ToString() == "")
            {
                rtn = String.Format("(select OpObjectID from SYS_UserOpScope where 1=0)");
            }
            else
            {
                rtn = "(" + this.Session["DeptScope"].ToString() + ")";
            }
            return rtn;
        }

        /// <summary>
        /// 获取片区权限查询范围（需和部门权限范围配合使用）
        /// </summary>
        /// <returns></returns>
        protected string GetAreaRightCondition()
        {
            //string rtn = "(select OpObjectID from SYS_UserOpScope Where DeptOrArea=1 and EmpID='" + this.LogonUser.EmpID + "')";
            string rtn = "";
            if (this.Session["AreaScope"] == null || this.Session["AreaScope"].ToString() == "")
            {
                rtn = String.Format("(select OpObjectID from SYS_UserOpScope where 1=0)");
            }
            else
            {
                rtn = "(" + this.Session["AreaScope"].ToString() + ")";
            }
            return rtn;
        }

        /// <summary>
        /// 获取当前用户参与的成交

        /// </summary>
        /// <returns></returns>
        protected string GetPersonalRightCondition()
        {
            string rtn = "(select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID + "' "
                + "union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID + "')";
            return rtn;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected string GetPersonalRightConditionForCert()
        {
            string sql = String.Format(@"select empid from F_Forward where forwardempid ='{0}' ", this.LogonUser.EmpID);

            string empScope = WF.Common.CentaUtil.GetTableColString(this.DataManager, sql, "EmpID");
            if (empScope.Trim() != "")
            {
                empScope = "(" + empScope + ")";
                sql = "(select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID + "' OR EmpID IN " + empScope
                    + " union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID + "' OR EmpID IN " + empScope
                    + " Union Select b.ContractID From CT_CommisionAdjustAssigns a Inner Join CT_CommisionAdjust b on a.AdjustID=b.AdjustID "
                    + " Where a.CommRatePer<>0 and a.EmpID='" + this.LogonUser.EmpID + "' OR a.EmpID IN " + empScope + ")";
            }
            else
            {
                sql = "(select ContractID from CT_ContractCommisionAssigns where EmpID='" + this.LogonUser.EmpID + "' "
                    + " union select ContractID from CT_Contract where EmpID='" + this.LogonUser.EmpID + "'"
                    + " Union Select b.ContractID From CT_CommisionAdjustAssigns a Inner Join CT_CommisionAdjust b on a.AdjustID=b.AdjustID "
                    + " Where a.CommRatePer<>0 and a.EmpID='" + this.LogonUser.EmpID + "')";
            }


            string rtn = WF.Common.CentaUtil.GetTableColString(this.DataManager, sql, "ContractID");

            if (rtn.Trim() != "")
            {
                rtn = " (" + rtn + ") ";
            }
            else
            {
                rtn = " ('') ";
            }
            return rtn;
        }
        #endregion

        #region 提交设置
        /// <summary>
        /// 设置提交按钮，用于数据有效性校验和权限检查

        /// </summary>
        /// <param name="submit"></param>
        protected void SetSubmitButton(Button submit)
        {
            this.SetSubmitButton(submit, true);
        }

        /// <summary>
        /// 设置提交按钮
        /// </summary>
        /// <param name="submit"></param>
        /// <param name="isValidateButton">是否对按钮点击事件进行有效性检查</param>
        protected void SetSubmitButton(Button submit, bool isValidateButton)
        {
            this.submitButtons.Add(submit);
            if (isValidateButton)
            {
                submit.Attributes.Add("onclick", "return OnFormSubmit();");
            }
        }

        /// <summary>
        /// 设置提交按钮
        /// </summary>
        /// <param name="submit"></param>
        /// <param name="isValidateButton">是否进行有效性校验</param>
        /// <param name="isConfirm">是否增加确认提醒</param>
        protected void SetSubmitButton(Button submit, bool isValidateButton, bool isConfirm)
        {
            this.submitButtons.Add(submit);
            if (isValidateButton)
            {
                if (isConfirm)
                {
                    submit.Attributes.Add("onclick", "if(OnFormSubmit()){ return confirm('确定执行此项操作吗？'); } else return false;");
                }
                else
                {
                    submit.Attributes.Add("onclick", "return OnFormSubmit();");
                }
            }
            else
            {
                if (isConfirm)
                {
                    submit.Attributes.Add("onclick", "return confirm('确定执行此项操作吗？');");
                }
            }
        }

        protected void SetButtonConfirm(Button button)
        {
            button.Attributes.Add("onclick", "return confirm('确定执行此项操作吗？');");
        }

        protected void SetButtonConfirm(LinkButton button)
        {
            button.Attributes.Add("onclick", "return confirm('确定执行此项操作吗？');");
        }
        //
        //		protected void SetButtonConfirm(Button button ,string actionName)
        //		{
        //			button.Attributes.Add("onclick" ,String.Format("return confirm('确定执行[{0}]操作吗？');" ,actionName));
        //		}

        protected void SetButtonClose(Button button)
        {
            button.Attributes.Add("onclick", "window.close();");
            button.Text = "关 闭";
        }



        #endregion


        #region 控件与业务实体

        /// <summary>
        /// 根据BusinessEntity设置控件初始值，用于浏览和修改

        /// 控件ID命名必须符合项目命名规范
        /// </summary>
        /// <param name="bizEntity"></param>
        protected void SetControlsByEntity(BusinessEntiry bizEntity)
        {
            string colName, controlValue, controlType;
            foreach (System.Web.UI.Control control in this.Controls)
            {
                controlType = control.GetType().Name;
                if (control.ID != null)
                {
                    colName = control.ID.Substring(3);
                    controlValue = bizEntity.GetPropertyValue(colName);
                    switch (controlType)
                    {
                        case "TextBox":
                            TextBox t = (TextBox)control;
                            t.Text = controlValue;
                            break;
                        case "DropDownList":
                            DropDownList l = (DropDownList)control;
                            try
                            {
                                l.SelectedValue = controlValue;
                            }
                            catch { }
                            break;
                        case "RadioButtonList":
                            RadioButtonList r = (RadioButtonList)control;
                            try
                            {
                                r.SelectedValue = controlValue;
                            }
                            catch { }
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 根据控件设置BusinessEntity属性值，用于新增、修改提交后的处理

        /// 控件ID命名必须符合项目命名规范
        /// </summary>
        /// <param name="bizEntity"></param>
        protected void SetEntityByControls(BusinessEntiry bizEntity)
        {
            string colName, controlValue, controlType;

            foreach (System.Web.UI.Control control in this.Controls)
            {
                controlType = control.GetType().Name;
                if (control.ID != null)
                {
                    colName = control.ID.Substring(3);
                    switch (controlType)
                    {
                        case "TextBox":
                            TextBox t = (TextBox)control;
                            controlValue = t.Text;
                            break;
                        case "DropDownList":
                            DropDownList l = (DropDownList)control;
                            controlValue = l.SelectedValue;
                            break;
                        case "RadioButtonList":
                            RadioButtonList r = (RadioButtonList)control;
                            controlValue = r.SelectedValue;
                            break;
                        default:
                            controlValue = null;
                            break;
                    }
                    if (controlValue != null)
                    {
                        bizEntity.SetProperty(colName, controlValue);
                    }
                }
            }
        }

        /// <summary>
        /// 根据BusinessEntity设置ControlEx（值，只读状态等）

        /// </summary>
        /// <param name="control"></param>
        protected void SetControlsExByEntity(System.Web.UI.Control control, BusinessEntiry be)
        {
            foreach (System.Web.UI.Control c in control.Controls)
            {
                if (c.ID != null && c.GetType().Namespace == "Com.UI.Web" && this.HaveInterface(c, "IControlEx"))
                {
                    IControlEx bc = (IControlEx)c;
                    bc.SetControlByBusinessEntity(be);
                }
                else
                {
                    SetControlsExByEntity(c, be);
                }
            }
        }

        /// <summary>
        /// 根据ControlsEx设置BusinessEntity
        /// </summary>
        /// <param name="control"></param>
        protected void SetEntityByControlsEx(System.Web.UI.Control control, BusinessEntiry be)
        {
            foreach (System.Web.UI.Control c in control.Controls)
            {
                if (c.ID != null && c.GetType().Namespace == "Com.UI.Web" && this.HaveInterface(c, "IControlEx"))
                {
                    IControlEx bc = (IControlEx)c;
                    bc.SetBusinessEntityProperty(be);
                }
                else
                {
                    SetEntityByControlsEx(c, be);
                }
            }
        }

        /// <summary>
        /// 判断控件是否包含interfaceName接口
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        private bool HaveInterface(System.Web.UI.Control control, string interfaceName)
        {
            Type t = control.GetType().GetInterface(interfaceName);
            return (t != null);
        }
        #endregion


        #region 与工作流相关
        protected void LoadWFParam()
        {


        }
        #endregion


        /// <summary>
        /// 将页面以Word方式呈现
        /// </summary>
        /// <param name="filename"></param>
        protected void ExportToWord(string filename)
        {
            //一、定义文档类型、字符编码

            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "gb2312";

            Response.AppendHeader("Content-Disposition", "online;filename=" + Server.UrlEncode(filename));
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.ContentType = "application/ms-Word";
            this.EnableViewState = false;

        }



    }
}

